package server.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import plug.result.ReqPage;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.ApplyDao;
import server.dao.UserBlanceDao;
import server.dao.UserDepositDao;
import server.dao.UsersDao;
import server.model.dto.ApplyDto;
import server.model.entity.Apply;
import server.model.entity.BlanceRecord;
import server.model.entity.UserBlance;
import server.model.entity.Users;
import server.service.UserBlanceService;
import server.tool.tool.BeanUtil;

import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Api
@RestController
@RequestMapping("v1/api/apply")
@CrossOrigin(origins = "*")
public class ApplyController {
    @Autowired
    ApplyDao applyDao;
    @Autowired
    UsersDao usersDao;
    @Autowired
    UserBlanceService userBlanceService;
    @Autowired
    UserBlanceDao userBlanceDao;
    @Autowired
    UserDepositDao userDepositDao;

    @PostMapping("/all")
    @CrossOrigin(origins = "*")
    public RetResult findAll(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        Apply apply = new Apply();
        if (StringUtils.isNotBlank(req.getString("name"))) {
            List<Users> us = usersDao.findByNameLike(req.getString("name"));
            if (!us.isEmpty()) {
                apply.setUserId(us.get(0).getId());
            }
        }
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("userId", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Apply> example = Example.of(apply, matcher);
        Page<Apply> pages = applyDao.findAll(example, pageable);
        List<Apply> pageList = pages.getContent();
        List<ApplyDto> dtos = Lists.newLinkedList();
        pageList.forEach(it -> {
            ApplyDto dto = BeanUtil.convertToBean(it, ApplyDto.class);
            dto.setUsers(usersDao.findById(it.getUserId()).get());
            dto.setUserDeposit(userDepositDao.findById(it.getUserSiteId()).get());
            dtos.add(dto);
        });
        return RetResponse.makeRsp(0, "成功", dtos, (int) pages.getTotalElements());
    }


    @PostMapping("/status/{applyId}")
    public RetResult status(@PathVariable String applyId, boolean status) {
        Apply apply = applyDao.findById(applyId).get();
        if (apply.getType().equals(Apply.Type.PAY) || apply.getType().equals(Apply.Type.NO)) {
            return RetResponse.makeErrRsp("不允许更改");
        }
        if (status) {
            UserBlance ub = userBlanceDao.findByTypeAndUserId(UserBlance.Type.RMB, apply.getUserId());
            ub.setFrostMoney(ub.getFrostMoney().subtract(apply.getMoney()));
            ub.setMoney(ub.getMoney().add(apply.getMoney()));
            userBlanceDao.save(ub);
            userBlanceService.insBlance(apply.getUserId(),apply.getMoney(),UserBlance.Type.RMB, BlanceRecord.Type.DEPOSIT);
            apply.setType(Apply.Type.PAY);
            applyDao.save(apply);
        } else {
            UserBlance ub = userBlanceDao.findByTypeAndUserId(UserBlance.Type.RMB, apply.getUserId());
            ub.setFrostMoney(ub.getFrostMoney().subtract(apply.getMoney()));
            ub.setMoney(ub.getMoney().add(apply.getMoney()));
            userBlanceDao.save(ub);
            apply.setType(Apply.Type.NO);
            applyDao.save(apply);
        }
        return RetResponse.makeOKRsp();
    }
}
